package com.example.viewtest.ActivityGroup;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;

import com.example.viewtest.R;
import com.example.viewtest.Tools.BaseActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class JSONActivity extends BaseActivity {
    TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jsonactivity);
        Button button1 = this.findViewById(R.id.button_json);
        Button button2 = this.findViewById(R.id.button_threadPool);
        mTextView = this.findViewById(R.id.get_json_text);

        checkNeedPermissions();

        button1.setOnClickListener(v -> {
            setJSONData();
        });
        button2.setOnClickListener(v -> {
            serThreadPool();
        });
    }

    private void setJSONData(){
        try {
            // 首先最外层是{}，是创建一个对象
            JSONObject person = new JSONObject();
            // 第一个键phone的值是数组，所以需要创建数组对象
            JSONArray phone = new JSONArray();
            phone.put("12345678").put("87654321");
            person.put("phone", phone);

            person.put("name", "yuanzhifei89");
            person.put("age", 100);
            // 键address的值是对象，所以又要创建一个对象
            JSONObject address = new JSONObject();
            address.put("country", "china");
            address.put("province", "jiangsu");
            person.put("address", address);
            person.put("married", false);

            File  fileDir = getFilesDir();
            File textfile = new File(fileDir,"textfile.txt");
            File jsonfile = new File(fileDir,"jsontest.json");
            FileWriter fw = new FileWriter(jsonfile);
            fw.write(String.valueOf(person));
            Log.d("JSONObject的字符串类型：",String.valueOf(person));
            fileDir.createNewFile();
            fw.flush();

            String externalStoragePublicDirectory = Environment.getExternalStoragePublicDirectory
                    (Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
            File file = new File(externalStoragePublicDirectory+"/bilibili");
            boolean result = file.mkdirs();
            Log.d("外部内存设备根目录下创建子目录 ：", "结果： "+result);
            file.createNewFile();
            File sdcardfile = new File(file,"childe_sdcardfile.json");
            FileWriter fileWriter = new FileWriter(sdcardfile);
            fileWriter.write(String.valueOf(person));
            fileWriter.flush();
        } catch (JSONException ex) {
            // 键为null或使用json不支持的数字格式(NaN, infinities)
            throw new RuntimeException(ex);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void serThreadPool(){
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor
                (4,8,1, TimeUnit.SECONDS,new LinkedBlockingQueue<>(10));

        for (int i=0;i<3;i++){
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Log.d("当前线程 ： ",Thread.currentThread().getName());
                    ReadFile();
                }
            };
            threadPoolExecutor.execute(runnable);
        }

    }

    public void ReadFile(){
        try{
            File filedir = getFilesDir();
            File readJsonFile = new File(filedir,"jsontest.json");
            BufferedReader bufferedReader = new BufferedReader(new FileReader(readJsonFile));
            StringBuilder JsonData=new StringBuilder();
            String s = null;
            while ((s = bufferedReader.readLine()) != null){
                JsonData.append(s);
            }
            bufferedReader.close();
            toJsonAndIsJson(JsonData.toString());

            File file = new File(Environment.getExternalStoragePublicDirectory
                    (Environment.DIRECTORY_DOWNLOADS).getAbsolutePath());
            File readFile = new File(file,"sdcardfile.json");
            BufferedReader bufferedReader1 = new BufferedReader(new FileReader(readFile));
            StringBuilder stringBuilder = new StringBuilder();
            String s1;
            while ((s1 = bufferedReader1.readLine()) != null){
                stringBuilder.append(s1);
            }
            bufferedReader1.close();
            toJsonAndIsJson(stringBuilder.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void toJsonAndIsJson(String s){
        try {
            JSONObject jsonObject = new JSONObject(s);
            JSONArray phone = jsonObject.getJSONArray("phone");
            int number1 = phone.getInt(0);
            int number2 = phone.getInt(1);
            Log.d("读取到的Json数据：",number1 + " and " + number2);
            String name = jsonObject.getString("name");
            String age = jsonObject.getString("age");
            Log.d("读取到的Json数据：",name +" and "+age);
            JSONObject address = jsonObject.getJSONObject("address");
            String country = address.getString("country");
            String province = address.getString("province");
            boolean married = jsonObject.getBoolean("married");
            Log.d("读取到的Json数据：",country + " and " + province + " and " +married);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //在onCreate中申请权限
    private void checkNeedPermissions(){
        //6.0以上需要动态申请权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //多个权限一起申请
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE
            }, 1);
        }
    }


}